var FeedMaterialForm = function () {
  var template = /*html*/ `
    <div class="feed-material-form" v-loading.fullscreen.lock="loading">
      <template v-if="materialDetail!==null">
        <el-form :model="materialDetail" label-width="115px">
          <el-form-item label="物料名称">
            <span v-if="isRead||!getUpdateAuthority('materialName')">{{materialDetail.materialName}}</span>
            <el-autocomplete v-else class="form-input" v-model="materialDetail.materialName" :fetch-suggestions="function(){getSuggestionData(materialList,arguments)}"
              @change="searchMaterial"></el-autocomplete>
          </el-form-item>
          <el-form-item label="规格型号">
            <span v-if="isRead||!getUpdateAuthority('model')">{{materialDetail.model}}</span>
            <el-autocomplete v-else class="form-input" v-model="materialDetail.model" :fetch-suggestions="function(){getSuggestionData(modelList,arguments)}"
              @change="searchMaterial"></el-autocomplete>
          </el-form-item>
          <el-form-item label="编号">
            <span v-if="isRead||!getUpdateAuthority('color')">{{materialDetail.color}}</span>
            <el-autocomplete v-else class="form-input" v-model="materialDetail.color" :fetch-suggestions="function(){getSuggestionData(colorList,arguments)}"
              @change="searchMaterial"></el-autocomplete>
          </el-form-item>
          <el-form-item label="供应商名称">
            <span v-if="isRead||!getUpdateAuthority('providerName')">{{materialDetail.providerName}}</span>
            <template v-else>
            <el-select filterable class="form-input" :class="{'form-input-btn':mode==='nonFeed'}" v-model="materialDetail.providerName" @change="searchMaterial">
              <el-option v-for="(customerName,index) in customerNameList" :key="'customerName_'+index" :value="customerName" :label="customerName"></el-option>
            </el-select>
            <el-button v-if="mode==='nonFeed'" type="primary" class="addProvider" @click="toAddProvider">添加供应商</el-button>
            </template>
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-if="!isRead&&getUpdateAuthority('colorDescription')" class="form-input" v-model="materialDetail.colorDescription"></el-input>
            <span v-else>{{materialDetail.colorDescription}}</span>
          </el-form-item>
          <el-form-item label="物料部门">
            <el-select class="form-input" clearable filterable v-model="materialDetail.materialDept" value-key="materialDeptId" @change="materialDeptChange">
              <el-option v-for="dept in deptList" :key="dept.materialDeptId" :value="dept" :label="dept.materialDeptName"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <span>使用</span>
          </el-form-item>
          <el-form-item label="默认仓库">
            <span>{{materialDetail.defaultWarehouse}}</span>
          </el-form-item>
          <el-form-item label="物料类型">
            <span>{{materialDetail.materialType}}</span>
          </el-form-item>
          <el-form-item label="材质">
            <el-input v-if="!isRead&&canUpdate" class="form-input" v-model="materialDetail.material"></el-input>
            <span v-else>{{materialDetail.material}}</span>
          </el-form-item>
          <el-form-item v-if="materialDetail.materialType==='镜片'" label="透光率(%)">
            <el-input-number v-if="!isRead&&canUpdate" class="form-number-input" v-model="materialDetail.transmittance" controls-position="right" :min="0" :max="100" :precision="0">
            </el-input-number>
            <span v-else>{{materialDetail.transmittance}}</span>
          </el-form-item>
          <el-form-item label="单位">
            <el-select v-if="!isRead&&canUpdate" class="form-input" :filterable="true" v-model="materialDetail.unit" @change="unitChange">
              <el-option v-for="(unit,index) in dropdownOption.unitList" :key="'unit_'+index" :value="unit" :label="unit"></el-option>
            </el-select>
            <span v-else>{{materialDetail.unit}}</span>
          </el-form-item>
          <el-form-item label="单价">
            <el-input-number v-if="!isRead&&canUpdate" class="form-number-input" v-model="materialDetail.unitPrice" controls-position="right" :min="0" :precision="2">
            </el-input-number>
            <span v-else>{{materialDetail.unitPrice}}</span>
          </el-form-item>
          <el-form-item label="计价单位是否和生产单位相同" class="equal-form-input">
            <span>{{equalList[materialDetail.isEquals]}}</span>
          </el-form-item>
          <el-form-item label="采购周期">
            <el-input-number v-if="!isRead&&canUpdate" class="form-number-input" v-model="materialDetail.procurementCycles" controls-position="right" :min="0" :precision="0">
            </el-input-number>
            <span v-else>{{materialDetail.procurementCycles}}</span>
          </el-form-item>
          <el-form-item label="投料数" v-if="mode==='feed'">
            <el-input-number v-if="!isRead&&materialDetail.isEquals===0" class="form-number-input" v-model="materialDetail.feedCount" controls-position="right" :min="0" :precision="4">
            </el-input-number>
            <span v-else>{{materialDetail.feedCount}}</span>
          </el-form-item>
        </el-form>
        <div class="form-btns">
          <el-button type="primary" @click="updateMaterial">保存</el-button>
          <el-button v-if="canCreatePre&&mode!=='feed'" type="primary" @click="createPrePurchaseOrder">生成预采购单</el-button>
        </div>

        <el-dialog append-to-body v-if="!isRead&&mode==='nonFeed'" title="添加供应商" :visible.sync="openCustomerForm" top="5vh">
          <div style="height: calc(80vh - 54px); overflow: auto">
            <customer-form v-if="openCustomerForm" :customer-type="1" @save-success="addCustomerAfter">
            </customer-form>
          </div>
        </el-dialog>
      </template>
    </div>
  `;

  return {
    props: {
      feed: {
        type: Object,
        required: true
      },
      dropdownOption: {
        type: Object,
        required: true
      },
      mode: {
        type: String,
        default: 'feed'
      }
    },

    mixins:[
      materialFormMixin('materialDetail')
    ],

    watch: {
      resetLoading: function (val) {
        if (!val) {
          var saveMode = this.saveMode;
          if (!this.saving) {
            return;
          }

          if (saveMode === 'update') {
            this.updateMaterial();
          } else if (saveMode === 'prePurchase') {
            this.createPrePurchaseOrder();
          }
        }
      }
    },

    data: function () {
      return {
        loading: false,
        resetLoading: false,
        saving: false,
        saveMode: '',
        materialDetail: null,
        materialDetailList: [],
        updateAuthority: null,
        materialList: [],
        modelList: [],
        colorList: [],
        customerNameList: [],
        deptList: [],
        canUpdate: true,
        isRead: false,
        canCreatePre: false,
        openCustomerForm: false,
        equalList: ['不相同', '相同']
      };
    },

    created: function () {
      this.loading = true;
      var self = this;
      this.initData().then(function (materialDetail) {
        if (materialDetail === null) {
          return;
        }
        Promise.all([
          self.setMaterialList(),
          self.setModelList(),
          self.setColorList(),
          self.setCustomerNameList(),
          self.setDeptList()
        ]).then(function () {
          self.resetMaterialName();
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      });
    },

    methods: {
      initData: function () {
        var mode = this.mode;
        if (mode === 'feed') {
          return this.initFeedData().then(function (materialDetail) {
            return materialDetail;
          });
        } else if (mode === 'nonFeed') {
          return this.initNonFeedData().then(function (materialDetail) {
            return materialDetail;
          });
        }
      },

      initFeedData: function () {
        var feed = this.feed;
        var postData = {
          materialCode: feed.materialCode
        };
        return this.resetMaterialData(postData).then(function (materialDetail) {
          return materialDetail;
        });
      },

      initNonFeedData: function () {
        var feed = this.feed;
        var self = this;

        var postData = {
          orderId: feed.orderNo,
          oldColor: feed.color,
          materialType: feed.materialType,
          oldModel: feed.materialModel,
          oldColorDescription: feed.colorDescription,
          oldMaterialFactory: feed.materialFactory
        };
        return ajaxRequest('advancePurchase/getAdvancePurchaseByDetail', postData).then(function (detail) {
          var materialDetail = null;
          if (detail === null) {
            self.canCreatePre = true;
            self.isRead = false;
            materialDetail = new FeedMaterialDetailModel(feed, 'orderFeed');
            self.setUpdateMainAuthority(materialDetail);
          } else {
            self.canCreatePre = false;
            self.isRead = true;
            materialDetail = new FeedMaterialDetailModel(detail, feed, 'prePurchaseFeed');
          }
          self.materialDetail = materialDetail;
          return materialDetail;
        }).catch(function () {
          return null;
        });
      },

      setUpdateMainAuthority: function (materialDetail) {
        var updateAuthority = {};
        var fields = ['materialName', 'color', 'colorDescription', 'providerName', 'model'];
        for (var i = 0; i < fields.length; i++) {
          var field = fields[i];
          var value = materialDetail[field];
          if (SysUtil.isEmpty(value)) {
            value = '';
          } else {
            value = value.trim();
          }
          if (value === '') {
            updateAuthority[field] = true;
          } else {
            updateAuthority[field] = false;
          }
        }
        this.updateAuthority = updateAuthority;
      },

      resetMaterialData: function (postData) {
        var self = this;
        this.resetLoading = true;
        var resMaterialDetail = this.materialDetail;
        return ModuleUtil.getFeedMaterialDetail(postData, this.feed, this.mode).then(function (materialDetailList) {
          var materialDetail = null;
          self.materialDetailList = materialDetailList;
          if (!SysUtil.isEmpty(materialDetailList)) {
            materialDetail = self.getMaterialDataByDept(materialDetailList);
          }

          if (materialDetail !== null) {
            if (!SysUtil.isEmpty(resMaterialDetail)) {
              materialDetail.colorDescription = resMaterialDetail.colorDescription;
            }
            self.materialDetail = materialDetail;
            self.canUpdate = false;
            self.canCreatePre = false;
          } else {
            self.canUpdate = true;
            self.canCreatePre = true;
          }
          self.resetLoading = false;
          return materialDetail;
        }).catch(function () {
          return null;
        });
      },

      materialDeptChange:function(){
        var resMaterialDetail = this.materialDetail;
        var materialDetail = this.getMaterialDataByDept();
        if (materialDetail !== null) {
          if (!SysUtil.isEmpty(resMaterialDetail)) {
            materialDetail.colorDescription = resMaterialDetail.colorDescription;
          }
          this.materialDetail = materialDetail;
          this.canUpdate = false;
          this.canCreatePre = false;
        } else {
          this.canUpdate = true;
          this.canCreatePre = true;
        }
      },

      getMaterialDataByDept: function (materialDetailList) {
        if (materialDetailList === undefined) {
          materialDetailList = this.materialDetailList;
        }

        var materialDetail = this.materialDetail;
        if (materialDetail === null) {
          return _.cloneDeep(materialDetailList[0]);
        }

        materialDetail = _.find(materialDetailList, function (obj) {
          return _.get(obj, 'materialDept.materialDeptId') === _.get(materialDetail, 'materialDept.materialDeptId');
        });
        if (materialDetail === undefined) {
          return null;
        }
        return _.cloneDeep(materialDetail);
      },

      setMaterialList: function () {
        var self = this;
        return DropdownUtil.getMaterialList().then(function (materialList) {
          self.materialList = materialList;
          return materialList;
        });
      },

      setModelList: function () {
        var self = this;
        return DropdownUtil.getModelList().then(function (modelList) {
          self.modelList = modelList;
          return modelList;
        });
      },

      setColorList: function () {
        var self = this;
        return DropdownUtil.getColorList().then(function (colorList) {
          self.colorList = colorList;
          return colorList;
        });
      },

      setCustomerNameList: function () {
        var self = this;
        return DropdownUtil.getCustomerNameList().then(function (customerNameList) {
          var providerName = self.materialDetail.providerName;
          if (providerName !== '' && customerNameList.indexOf(providerName) === -1) {
            customerNameList = [providerName];
            customerNameList.pushArray(customerNameList);
          }
          self.customerNameList = customerNameList;
          return customerNameList;
        });
      },

      setDeptList: function () {
        var self = this;
        return ajaxRequest('basicData/getDeptName', {
          view: 1
        }).then(function (deptList) {
          deptList = _.map(deptList, function (dept) {
            return {
              materialDeptId: dept.id,
              materialDeptName: dept.deptName
            };
          });
          self.deptList = deptList;
          return deptList;
        });
      },

      searchMaterial: function () {
        var materialDetail = this.materialDetail;
        if (!materialDetail.isChange()) {
          return;
        }
        materialDetail.saveOldData();
        var postData = materialDetail.getSearchObject();
        if (postData !== null) {
          this.resetMaterialData(postData);
        } else {
          this.canUpdate = true;
        }
      },

      unitChange: function () {
        var materialDetail = this.materialDetail;
        var unit = materialDetail.unit;
        if (unit === '付') {
          materialDetail.isEquals = 1;
        } else {
          materialDetail.isEquals = 0;
        }
      },

      getSuggestionData: function (suggestList, arr) {
        var queryString = arr[0];
        var cb = arr[1];
        if (queryString !== '') {
          suggestList = _.filter(suggestList, function (suggest) {
            return suggest.indexOf(queryString) !== -1;
          });
        }
        suggestList = _.map(suggestList, function (suggest) {
          return {
            value: suggest
          };
        });
        cb(suggestList);
      },

      updateMaterial: function () {
        if (this.resetLoading) {
          this.saving = true;
          this.saveMode = 'update';
          return;
        }
        this.saving = false;
        this.saveMode = '';

        var materialDetail = this.materialDetail;
        if (!materialDetail.checkValid(this.canUpdate)) {
          return;
        }

        var self = this;
        this.$confirm('确定要保存吗？', '温馨提示').then(function () {
          self.toUpdateMaterial(materialDetail);
        }).catch(function () {});
      },

      toUpdateMaterial: function (materialDetail) {
        var url, mode = this.mode;
        var postData = materialDetail.getObject(this.canUpdate);
        if (mode === 'feed') {
          url = 'order/updateFeedDetailMaterial';
        } else if (mode === 'nonFeed') {
          url = 'productionUnitFeed/updateBasicDataAndOrderInfoDetailOnBatch';
          postData.haveYltsTotal = materialDetail.haveYltsTotal;
        }
        this.loading = true;
        var self = this;

        ajaxRequest(url, postData).then(function (msg) {
          self.loading = false;
          if (mode === 'nonFeed') {
            msg = '物料保存成功';
          }

          self.$alert(msg, '信息', {
            callback: function () {
              self.$emit('update-success');
            }
          });
        }).catch(function () {
          self.loading = false;
        });
      },

      toAddProvider: function () {
        this.openCustomerForm = true;
      },

      addCustomerAfter: function (customer) {
        this.openCustomerForm = false;
        var self = this;
        this.loading = true;
        this.setCustomerNameList().then(function () {
          self.loading = false;
          self.materialDetail.providerName = customer.customerName;
          self.canUpdate = true;
        }).catch(function () {
          self.loading = false;
        });
      },

      createPrePurchaseOrder: function () {
        if (this.resetLoading) {
          this.saving = true;
          this.saveMode = 'prePurchase';
          return;
        }
        this.saving = false;
        this.saveMode = '';

        var materialDetail = this.materialDetail;
        if (!materialDetail.checkValid(this.canUpdate)) {
          return;
        }
        var feed = this.feed;
        var self = this;
        this.$prompt('请输入预采购数', '预采购数', {
          inputValidator: function (value) {
            if (value === null) {
              return false;
            }
            if (value.endsWith('.')) {
              return false;
            }
            value = Number(value);
            if (isNaN(value)) {
              return false;
            }
            if (value <= 0) {
              return false;
            }
            var count = _.round(value, 2);
            return count === value;
          },
          inputErrorMessage: '请输入合法数字',
          inputValue: feed.feedTotal + ''
        }).then(function (option) {
          var value = option.value;
          value = Number(value);
          self.toCreateOrder(value);
        }).catch(function () {});
      },

      toCreateOrder: function (count) {
        var materialDetail = this.materialDetail;
        var postData = materialDetail.getPrePurchaseObj(this.feed, count);

        this.loading = true;
        var self = this;
        ajaxRequest('advancePurchase/addAdvancePurchase', postData).then(function (msg) {
          self.loading = false;
          self.$alert('预采购单生产成功', '信息', {
            callback: function () {
              self.$emit('close-dialog');
            }
          });
        }).catch(function () {
          self.loading = false;
        });
      },

      getUpdateAuthority: function (field) {
        var updateAuthority = this.updateAuthority;
        var canUpdate = true;
        if (field === '物料名称') {
          canUpdate = this.isUpdateMaterialName;
        }

        if (updateAuthority === null) {
          return canUpdate;
        }

        var authority = updateAuthority[field];
        if (authority === undefined) {
          return canUpdate;
        }
        return authority && canUpdate;
      }
    },
    components: {
      CustomerForm: CustomerForm
    },
    template: template
  };
}();
